import sys

from PySide6.QtCore import Signal
from PySide6.QtWidgets import QDialog, QApplication, QMessageBox

from backend.db.database import SessionLocal
from backend.services.certificate_services import CertificateServices
from front.ui.ui_creat_certificate import Ui_Dialog


class CreatCertificate(QDialog, Ui_Dialog):
    remind = Signal()

    def __init__(self, parent=None):
        super().__init__(parent)
        self.setupUi(self)
        self.pushButton.clicked.connect(self.create_certificate)

    def create_certificate(self):
        """创建存单"""
        try:
            with SessionLocal() as session:
                certificate_service = CertificateServices(session)
                vip_text = self.vip_id_Edit.text().strip()
                certificate_text = self.certificate_data_Edit.text().strip()
                if not vip_text or not certificate_text:
                    QMessageBox.warning(self, "警告", "缺少ID或存单内容")
                    return
                a = {"member_id": vip_text, "certificates": certificate_text}
                certificate_service.add_certificate(**a)
                QMessageBox.information(self, "成功", "存单添加成功")
                self.remind.emit()
                self.close()
                self.deleteLater()
        except ValueError:
            QMessageBox.warning(self, "警告", f"会员不存在")


if __name__ == '__main__':
    app = QApplication([])
    ex = CreatCertificate()
    ex.show()
    sys.exit(app.exec())
